//
//  LoginVM.swift
//  ProjectApp
//
//  Created by jack on 2021/1/11.
//

import Foundation
class LoginVM {
    let validateAccount: Observable<Bool>
    let validatePassword: Observable<Bool>
    let signupEnabled: Observable<Bool>
    let loginResult: Observable<(Bool, String)>
   
    
    init(input:(
            account: Observable<String>,
            password: Observable<String>,
            loginTap: Observable<Void>
    )) {
        
        /// 验证账号
        validateAccount = input.account.flatMap({ (account) -> Observable<Bool> in
            var flag = true
            if account.count < 5 {
                flag = false
            }
            return Observable.of(flag)
        })
        
        /// 验证密码
        validatePassword = input.password.flatMap({ (password) -> Observable<Bool> in
            var flag = true
            if password.count < 5 {
                flag = false
            }
            return Observable.of(flag)
        })
        
        /// 有效账号&有效密码则可以点击登录按钮
        signupEnabled = Observable.combineLatest(validateAccount, validatePassword){
            accountFlag, passwordFlag in
            accountFlag && passwordFlag
        }.distinctUntilChanged()
        .share(replay: 1)
        
        /// 合并账号和密码，组成元组
        let accountAndPassword = Observable.combineLatest(input.account, input.password) { (account: $0, password: $1) }
        // 登录按钮点击事件
        self.loginResult = input.loginTap.withLatestFrom(accountAndPassword).flatMapLatest { (pair) -> Observable<RespEntity<User>> in
            let observable: Observable<RespEntity<User>> = rxrequest(params: .Login(account: pair.account, password: pair.password), errorToast: true, hud: true)
            return observable
        }
        /// 登录接口返回数据进行Observable转换
        .flatMap({ (resp: RespEntity<User>) -> Observable<(Bool, String)> in
            if let _ = resp.data { // 返回有用户数据则判断为登录成功
                // TODO 保存用户信息
                return Observable.of((true, ""))
            } else {
                var msg = "网络信号差，请稍后重试"
                if let str = resp.msg { // 如果返回有提示信息(如：账号错误、密码错误等)则提示返回的信息
                    msg = str
                }
                return Observable.of((false, msg))
            }
        })
    }
}
